package com.gem.eolane.web;


import com.gem.eolane.config.AppConfig;
import com.gem.eolane.entity.Admin;
import com.gem.eolane.entity.Demo;
import com.gem.eolane.entity.PcbOffer;
import com.gem.eolane.entity.User;
import com.gem.eolane.service.AdminService;
import com.gem.eolane.service.BackstaService;
import com.gem.eolane.service.NewsService;
import com.gem.eolane.service.UserService;
import com.gem.eolane.utils.Enande;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gem.eolane.entity.News;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;

//后台拦截
@Controller
@RequestMapping("/a/u")
public class UBackInterfaceController {
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    @Autowired
    private NewsService newsService;

    @Autowired
    private BackstaService backstaService;

    @Autowired
    private AppConfig appConfig;

    //=====================李jingyang========================

    //用户的查询 返回用户列表（模糊查询）《分页》
    @RequestMapping("/queryUser")
    public String queryUser(String userName , Model model, Integer currentPage, HttpServletRequest request) {
        /*if(name == null){
            name = "";
        }*/
        if(currentPage==null){
            currentPage = 1;
        }
        int totalPage = userService.userTotalPage(userName);
        List<User> userList = userService.currentList(userName,currentPage);
        userList.forEach(System.out::print);
        //解密，关键key为：private static String password = "小子来破解啊";
        for (User user:userList) {//遍历所有数据，进行密码解密
            user.setPassword(Enande.decrypt(user.getPassword()));
        }
        model.addAttribute("userList",userList);
        model.addAttribute("currentPage",currentPage);
        model.addAttribute("totalPage",totalPage);
        //模糊字查询，回显出去
        model.addAttribute("keyword" ,userName);
        return "backstagepage/uselist";
    }

    //用户的禁用
    @RequestMapping("/banUser")
    public String banUser(Integer id , Integer delIdent) {
        userService.banUser(id,delIdent);
        return "redirect:queryUser";
    }


    //管理员列表 分页
    @RequestMapping("/admin")
    public String demo7(Model model, Integer currentPage,HttpSession session) {
        if (currentPage == null) {
            currentPage = 1;
        }
        //获取当前的admin信息
        Admin admin = (Admin) session.getAttribute("admin");
        System.out.println("当前账户为：" + admin);
        //获取当前管理员id
        Integer adminId = admin.getId();
        int totalPage = adminService.totalPage();
        List<Admin> adminList = adminService.findAdminList(currentPage);
        model.addAttribute("adminId",adminId);
        model.addAttribute("adminList", adminList);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("totalPage",totalPage);
        return "backstagepage/admin";
    }


    //添加管理员界面中转 中转至添加页面
    @RequestMapping("/addAdminLink")
    public String addAdminLink() {

        return "backstagepage/add_admin";
    }

    //添加管理员 添加完毕返回管理员列表
    @RequestMapping("/add_admin")
    public String addAdmin(Admin admin,Model model) {
        boolean flag = adminService.insertAdmin(admin.getAdminNumber(),admin.getPassword(),admin.getName());
        if(flag){
            return "redirect:admin";
        }else{
            model.addAttribute("flag",flag);
            return "backstagepage/add_admin";
        }

    }

    //禁用管理员 返回管理员列表
    @RequestMapping("/delete_admin")
    public String deleteAdmin(Integer id,Integer delIdent) {
        adminService.banAdmin(id,delIdent);
        return "redirect:admin";
    }

    //=====================李jingyang========================





    //=====================徐jianghui========================

    //从数据库读取数据显示在历史订单
    @RequestMapping("/listory")
    public String list(Model model, Demo demo, Integer page, Integer size) {
        if (page==null){
            page=1;
        }
        int curr = page;
        List<Demo> list = backstaService.listro(page,size);
        list.forEach(System.out::print);
        int count=backstaService.listroCount();
        //向前台发送所有数据
        model.addAttribute("list",list);
        //向前台发送数据总量
        model.addAttribute("count",count);
        //向前台发送当前页
        model.addAttribute("curr",curr);
        return "backstagepage/listory";
    }

    //从数据库读取数据进入历史订单详情页面
    @RequestMapping("/save")
    public String save(PcbOffer pcbOffer, Model model) {
        //根据点击按钮传过来的id查询当前id所有的数据
        List<PcbOffer> list = backstaService.findPcbList(pcbOffer.getId());
        PcbOffer pcbOffer1 = list.get(0);
        model.addAttribute("PcbOffer",pcbOffer1);
        return "backstagepage/Listrovalue";
    }


    //从数据库读取数据显示在PCB订单
    @RequestMapping("/pcb")
    public String Pcb(Model model, Integer page, Integer size) {
        if (page==null){
            page=1;
        }
        int curr = page;
        List<Demo> list = backstaService.demos(page,size);
        int count=backstaService.count();
        list.forEach(System.out::print);
        model.addAttribute("list",list);
        model.addAttribute("count",count);
        model.addAttribute("curr",curr);
        return "backstagepage/PCB";
    }

    //从数据库读取数据显示在PCB订单详情中
    @RequestMapping("/pcbDetail")
    public String pcbDetail(PcbOffer pcbOffer, Model model) {
        List<PcbOffer> list = backstaService.findPcbList(pcbOffer.getId());
        PcbOffer pcbOffer1 = list.get(0);
        model.addAttribute("PcbOffer",pcbOffer1);
        return "backstagepage/PCBvalue";
    }

    //批量删除历史订单数据
    @RequestMapping("/delete")
    public String delete(HttpServletRequest request){
        //获取到前台传过来的cheakbox的值
        String sids = request.getParameter("sids");
        System.out.println(sids);
        //转换为数组
        String[] s=sids.split(",");
        //转换为集合
        List<Integer> list = new ArrayList(Arrays.asList(s));
        backstaService.listdelreues(list);
        return "redirect:listory";
    }
    //批量删除pcb订单数据
    @RequestMapping("/deletes")
    public String deleteP(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //获取到前台传过来的cheakbox的值
        String sids = request.getParameter("sids");
        System.out.println(sids);
        //转换为数组
        String[] s=sids.split(",");
        //转换为集合
        List<Integer> list = new ArrayList(Arrays.asList(s));
        backstaService.listdelreues(list);
        return "redirect:pcb";
    }


    //根据表关联通过订单编号查找订单编号查询报价返回到pcb订单页面
    @RequestMapping("/finbyoid")
    public String finbyoid(HttpServletRequest request,Model model){
        List<Demo> list =backstaService.findbyoid(request.getParameter("keywords"));
        model.addAttribute("list",list);
        return "backstagepage/PCB";
    }

    //根据公司名称模糊查询
    @RequestMapping("/finComp")
    public String finComp(HttpServletRequest request,Model model,Integer page, Integer size){
        if (page==null){
            page=1;
        }
        int curr = page;
        String company=request.getParameter("company");
        List<Demo> list = backstaService.findComp(company,page,size);
        int count=backstaService.Comcount(company);
        list.forEach(System.out::print);
        model.addAttribute("list",list);
        model.addAttribute("count",count);
        model.addAttribute("curr",curr);
        return "backstagepage/PCB";
    }

    //======================徐jianghui============================


    //======================祁gangye==============================
    //新闻列表页面
    @RequestMapping("/newbook")
    public String demo5(Model model, News news, Integer pageIndex, Integer pageSize){
        IPage<News> pageList = newsService.findPageList(news,pageIndex,pageSize);
        model.addAttribute("newslist",pageList.getRecords());
        model.addAttribute("count",pageList.getTotal());
        model.addAttribute("curr",pageList.getCurrent());
        return "backstagepage/newbook";
    }


    //新闻表单页面
    @RequestMapping("/news/form")
    public String newsForm(News news, Model model,Integer id){
        if (id != null) {
            news = newsService.getById(id);
        }else {
            news = new News();
        }
        model.addAttribute("news",news);
        return "backstagepage/newsForm";
    }

    //保存新闻
    @ResponseBody
    @RequestMapping("/news/save")
    public String savenews(News news) {
        /*Date datetime =news.getReleaseTime();
        System.out.println("新闻： = [" + news + "]");
        System.out.println("时间 = [" + datetime + "]");*/
        news.setReleaseTime(new Date());
        newsService.saveNews(news);
        return "success";
    }

    /*//下架新闻
    @ResponseBody
    @RequestMapping("/news/delete")
    public String delete(Integer id) {
        newsService.removeById(id);
        return "redirect:newbook";
    }*/

    //下架新闻
    @RequestMapping("/deleteNews")
    public String deleteNews(String id) {
        System.out.println("户次吧删除的id"+id);
        newsService.deleteNewsById(Integer.parseInt(id));
        return "redirect:newbook";
    }


    //根据id查询新闻内容(预览)
    @RequestMapping("/newsPreviewl")
    public String newsPreviewl(Model model,String id){

        /* News news = new News();*/
        System.out.println("进来id"+id);

        //左侧导航栏公司新闻标题
        List<News> companyNewsList = /*newsService.findCompanyNewsDesc();*/null;
        //左侧导航栏行业新闻标题
        List<News> industryNewsList = /*newsService.findIndustryNewsDesc();*/null;

        /* int Id = Integer.valueOf(id);*/
        if(id != null && id.length() > 0) {
            News news = newsService.findNewBysubld(Integer.parseInt(id));
            model.addAttribute("news",news);
        } else {
            News news = newsService.preShowNews();
            model.addAttribute("news",news);
        }

        /* News news = *//*newsService.findNewsContent(Id);*//* new News();*/

        model.addAttribute("industryNewsList",industryNewsList);
        model.addAttribute("companyNewsList",companyNewsList);
        /* model.addAttribute("news",news);*/
        return "backstagepage/newsPreviewl";

    }


    //确认新闻提交发布
    @RequestMapping("/confirmSubmit")
    public String confirmSubmit(String subId){
        newsService.confirmSubmit(Integer.parseInt(subId));
        return "redirect:newbook";
    }
    //返回重新修改页面
    @RequestMapping("/backToChange")
    public String backToChange(Model model,String subId){
        newsService.backUp(Integer.parseInt(subId));
        System.out.println("闯进来的修改的id"+subId);
        News news = newsService.findNewBysubld(Integer.parseInt(subId));
        System.out.println("修改的news"+news);
        model.addAttribute("news",news);
        return "backstagepage/newsForm";
    }

    @RequestMapping("/upload/editor")
    @ResponseBody
    public Object editor(MultipartFile file) {
        String fileName = "";
        if (!file.isEmpty()) {
            //返回的是字节长度，1M=1024k=1048756字节  也就是if(fileSize<5*1048756)
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            fileName = System.currentTimeMillis() + suffix;
            String saveFileName = appConfig.getFilepath() + "/eolane/news/" + fileName;
            System.out.println("filePath" + saveFileName);
            File dest = new File(saveFileName);
            if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest); //保存文件
            } catch (IOException e) {
                e.printStackTrace();
                return new WangEditorResponse("1", "上传失败" + e.getMessage());
            }
        }else {
            return new WangEditorResponse("1","上传出错");
        }
        String imgUrl = appConfig.getUrlpath() + "eolane/news/" + fileName;
        String img = fileName;
        List<String> data = new ArrayList<>();
        data.add(imgUrl);
        data.add(img);
        return new WangEditorResponse("0",data);
    }

    @Data
    private class WangEditorResponse{
        String errno;
        List<String> data;

        public WangEditorResponse(String errno, List<String> data) {
            this.errno = errno;
            this.data = data;
        }

        public WangEditorResponse(String errno,String data) {
            this.errno = errno;
            this.data = new ArrayList<>();
            this.data.add(data);
        }
    }

    //======================祁gangye==============================



    //======================公共页面===============================

    //后台退出登录
    @RequestMapping("/retirada")
    public String demo10(HttpSession session) {
        session.invalidate();
        return "redirect:/a/t/hlogin";
    }

    //后台返回快捷打样
    @RequestMapping("/relayout")
    public String demo11() {
        return "backstagepage/Layout";
    }

    //后台快捷打样订单详情
    @RequestMapping("/laydetalles")
    public String demo14() {
        return "backstagepage/Layoutvalue";
    }


    //后台添加新闻
    @RequestMapping("/addnews")
    public String add() {
        return "backstagepage/add_categroy";
    }

    //后台新闻详情
    @RequestMapping("/newdetail")
    public String filmForm() {
        return "backstagepage/newdetalle";
    }

    //后台首页界面
    @RequestMapping("/hindex")
    public String hindex(HttpSession session, Authentication authentication,Model model){
        String adminNumber = authentication.getName();
        System.out.println("ashdsdhrfhdsadfjwqd   "+ adminNumber);
        Admin admin = adminService.findQueryUser(adminNumber);
        session.setAttribute("admin",admin);
        model.addAttribute("admin",admin);
        return "backstagepage/index";
    }

}
